package com.example.demo.web;


import com.example.demo.GlobalException.BizException;
import com.example.demo.GlobalException.CommonEnum;
import com.example.demo.redisToken.RedisToken;
import com.example.demo.util.ResultBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


@RestController
public class Main {

    RedisToken redisToken;

    public Main(RedisToken redisToken) {
        this.redisToken = redisToken;
    }

    /**
     * 模拟登陆
     * @param userName 用户名
     * @param passWord 密码
     * @return 返回token
     */
    @RequestMapping("/login")
    public ResultBody login(String userName, String passWord) {
        if ("123".equals(userName) && "123456".equals(passWord)) {
            // 模拟获取用户信息
            String toke = redisToken.createToken("123","123",1,"127.0.0.1");
            // 返回token给前端保存以便之后访问携带上token
            return ResultBody.success(toke);
        }
        throw new BizException(CommonEnum.BODY_NOT_MATCH);
    }

    /**
     * 模拟登出
     * @param request 默认前端的token放在请求头，在请求头里获取
     * @return 成功信息。
     */
    @RequestMapping("/logOut")
    public ResultBody logOut(HttpServletRequest request) {
        redisToken.logOut(request);
        return ResultBody.success();
    }

    /**
     * 模拟从token中获取用户信息
     * @param request
     * @return
     */
    @RequestMapping("/Info")
    public String getUserInfo(HttpServletRequest request) {
        String id = (String) redisToken.getIdFromToken(request);
        Integer role = redisToken.getRoleFromToken(request);
        String userName = redisToken.getUsernameFromToken(request);
        String ip = redisToken.getIpFromToken(request);
        return id + role + userName + ip;
    }

}
